<template>
	<view class="profile-container">
		<!-- 用户信息区域 -->
		<view class="user-info">
			<view class="avatar">
				<text class="avatar-text">🔗</text>
			</view>
			<view class="user-details">
				<text class="username">蓝牙设备管理</text>
				<text class="user-desc">已连接设备: {{ connectedDevices.length }} 个</text>
			</view>
		</view>
		
		<!-- 统计信息 -->
		<view class="stats-section">
			<view class="stat-item">
				<text class="stat-number">{{ totalScannedDevices }}</text>
				<text class="stat-label">扫描设备总数</text>
			</view>
			<view class="stat-item">
				<text class="stat-number">{{ connectedDevices.length }}</text>
				<text class="stat-label">当前连接设备</text>
			</view>
			<view class="stat-item">
				<text class="stat-number">{{ historyDevices.length }}</text>
				<text class="stat-label">历史连接设备</text>
			</view>
		</view>
		
		<!-- 已连接设备列表 -->
		<view class="section">
			<view class="section-header">
				<text class="section-title">当前连接设备</text>
				<text class="section-count">{{ connectedDevices.length }}</text>
			</view>
			<scroll-view class="device-list" scroll-y v-if="connectedDevices.length > 0">
			<view 
				v-for="device in connectedDevices" 
				:key="device.deviceId" 
				class="device-item connected"
				@tap="goToDeviceDetail(device)"
			>
				<view class="device-icon">
					<text class="icon">📱</text>
				</view>
				<view class="device-info">
					<text class="device-name">{{ device.name || '未知设备' }}</text>
					<text class="device-id">{{ device.deviceId }}</text>
					<text class="device-status">已连接</text>
				</view>
				<view class="action-buttons">
					<button class="detail-btn" @tap.stop="goToDeviceDetail(device)">
						详情
					</button>
					<button class="disconnect-btn" @tap.stop="disconnectDevice(device)">
						断开
					</button>
				</view>
			</view>
			</scroll-view>
			<view class="empty-state" v-else>
				<text class="empty-text">暂无连接设备</text>
			</view>
		</view>
		
		<!-- 历史连接设备 -->
		<view class="section">
			<view class="section-header">
				<text class="section-title">历史连接设备</text>
				<text class="section-count">{{ historyDevices.length }}</text>
			</view>
			<scroll-view class="device-list" scroll-y v-if="historyDevices.length > 0">
				<view 
					v-for="device in historyDevices" 
					:key="device.deviceId" 
					class="device-item history"
					@tap="connectHistoryDevice(device)"
				>
					<view class="device-icon">
						<text class="icon">💾</text>
					</view>
					<view class="device-info">
						<text class="device-name">{{ device.name || '未知设备' }}</text>
						<text class="device-id">{{ device.deviceId }}</text>
						<text class="device-time">最后连接: {{ formatTime(device.lastConnectTime) }}</text>
					</view>
					<button class="connect-btn" @tap.stop="connectHistoryDevice(device)">
						连接
					</button>
				</view>
			</scroll-view>
			<view class="empty-state" v-else>
				<text class="empty-text">暂无历史连接设备</text>
			</view>
		</view>
		
		<!-- 操作按钮 -->
		<view class="action-buttons">
			<button class="clear-btn" @tap="clearHistory" :disabled="historyDevices.length === 0">
				清空历史记录
			</button>
			<button class="scan-btn" @tap="goToHome">
				返回首页扫描
			</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				connectedDevices: [],
				historyDevices: [],
				totalScannedDevices: 0
			}
		},
		
		onShow() {
			this.loadDevicesData()
		},
		
		methods: {
			// 加载设备数据
			loadDevicesData() {
				// 加载当前连接设备
				try {
					const connected = uni.getStorageSync('connectedDevices') || []
					this.connectedDevices = connected
				} catch (error) {
					console.error('加载连接设备失败:', error)
				}
				
				// 加载历史设备
				try {
					const history = uni.getStorageSync('historyDevices') || []
					this.historyDevices = history
				} catch (error) {
					console.error('加载历史设备失败:', error)
				}
				
				// 加载扫描统计
				try {
					const stats = uni.getStorageSync('scanStats') || {}
					this.totalScannedDevices = stats.totalScanned || 0
				} catch (error) {
					console.error('加载统计信息失败:', error)
				}
			},
			
			// 断开设备连接
			async disconnectDevice(device) {
				try {
					uni.showLoading({
						title: '断开中...'
					})
					
					await uni.closeBLEConnection({
						deviceId: device.deviceId
					})
					
					// 从连接设备列表中移除
					this.connectedDevices = this.connectedDevices.filter(
						d => d.deviceId !== device.deviceId
					)
					
					// 更新本地存储
					uni.setStorageSync('connectedDevices', this.connectedDevices)
					
					// 添加到历史记录
					this.addToHistory(device)
					
					uni.hideLoading()
					uni.showToast({
						title: '已断开连接',
						icon: 'success'
					})
					
				} catch (error) {
					console.error('断开连接失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: '断开失败',
						icon: 'none'
					})
				}
			},
			
			// 添加到历史记录
			addToHistory(device) {
				try {
					let history = uni.getStorageSync('historyDevices') || []
					
					// 移除已存在的记录
					history = history.filter(d => d.deviceId !== device.deviceId)
					
					// 添加新记录
					history.unshift({
						...device,
						lastConnectTime: new Date().getTime()
					})
					
					// 限制历史记录数量
					if (history.length > 50) {
						history = history.slice(0, 50)
					}
					
					uni.setStorageSync('historyDevices', history)
					this.historyDevices = history
					
				} catch (error) {
					console.error('保存历史记录失败:', error)
				}
			},
			
			// 连接历史设备
			connectHistoryDevice(device) {
				uni.showModal({
					title: '连接设备',
					content: `是否要连接设备 "${device.name || '未知设备'}"？`,
					success: (res) => {
						if (res.confirm) {
							// 跳转到首页并触发连接
							uni.switchTab({
								url: '/pages/index/index',
								success: () => {
									// 通过全局事件传递设备信息
									uni.$emit('connectDevice', device)
								}
							})
						}
					}
				})
			},
			
			// 清空历史记录
			clearHistory() {
				uni.showModal({
					title: '确认清空',
					content: '确定要清空所有历史连接记录吗？',
					success: (res) => {
						if (res.confirm) {
							uni.setStorageSync('historyDevices', [])
							this.historyDevices = []
							uni.showToast({
								title: '历史记录已清空',
								icon: 'success'
							})
						}
					}
				})
			},
			
	// 返回首页
	goToHome() {
		uni.switchTab({
			url: '/pages/index/index'
		})
	},
	
	// 跳转到设备详情页面
	goToDeviceDetail(device) {
		uni.navigateTo({
			url: '/pages/detail/detail?device=' + encodeURIComponent(JSON.stringify(device))
		})
	},
			
			// 格式化时间
			formatTime(timestamp) {
				if (!timestamp) return '未知时间'
				const date = new Date(timestamp)
				const now = new Date()
				const diff = now - date
				
				if (diff < 60000) { // 1分钟内
					return '刚刚'
				} else if (diff < 3600000) { // 1小时内
					return Math.floor(diff / 60000) + '分钟前'
				} else if (diff < 86400000) { // 1天内
					return Math.floor(diff / 3600000) + '小时前'
				} else {
					return date.getMonth() + 1 + '月' + date.getDate() + '日'
				}
			}
		}
	}
</script>

<style scoped>
	.profile-container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	/* 用户信息区域 */
	.user-info {
		display: flex;
		align-items: center;
		background: white;
		padding: 40rpx 30rpx;
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 60rpx;
		overflow: hidden;
		margin-right: 30rpx;
		background: linear-gradient(135deg, #007AFF, #5856D6);
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.avatar-text {
		font-size: 50rpx;
		color: white;
	}
	
	.user-details {
		flex: 1;
	}
	
	.username {
		display: block;
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.user-desc {
		display: block;
		font-size: 28rpx;
		color: #666;
	}
	
	/* 统计信息 */
	.stats-section {
		display: flex;
		justify-content: space-between;
		background: white;
		padding: 30rpx;
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.stat-item {
		text-align: center;
		flex: 1;
	}
	
	.stat-number {
		display: block;
		font-size: 40rpx;
		font-weight: bold;
		color: #007AFF;
		margin-bottom: 10rpx;
	}
	
	.stat-label {
		display: block;
		font-size: 24rpx;
		color: #999;
	}
	
	/* 区域样式 */
	.section {
		background: white;
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.section-count {
		font-size: 28rpx;
		color: #007AFF;
		background: #f0f8ff;
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
	}
	
	/* 设备列表 */
	.device-list {
		max-height: 400rpx;
	}
	
	.device-item {
		display: flex;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.device-item:last-child {
		border-bottom: none;
	}
	
	.device-item.connected {
		border-left: 8rpx solid #4cd964;
	}
	
	.device-item.history {
		border-left: 8rpx solid #ff9500;
	}
	
	.device-icon {
		width: 80rpx;
		height: 80rpx;
		border-radius: 40rpx;
		background: #f0f0f0;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 30rpx;
	}
	
	.icon {
		font-size: 36rpx;
	}
	
	.device-info {
		flex: 1;
	}
	
	.action-buttons {
		display: flex;
		gap: 10rpx;
	}
	
	.action-buttons {
		display: flex;
		gap: 10rpx;
	}
	
	.device-name {
		display: block;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
	}
	
	.device-id {
		display: block;
		font-size: 24rpx;
		color: #666;
		margin-bottom: 5rpx;
	}
	
	.device-status, .device-time {
		display: block;
		font-size: 24rpx;
		color: #999;
	}
	
	.connect-btn, .disconnect-btn, .detail-btn {
		background-color: #007AFF;
		color: white;
		border-radius: 8rpx;
		font-size: 24rpx;
		padding: 15rpx 25rpx;
	}
	
	.disconnect-btn {
		background-color: #ff3b30;
	}
	
	.detail-btn {
		background-color: #34c759;
	}
	
	/* 空状态 */
	.empty-state {
		padding: 60rpx 30rpx;
		text-align: center;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
	
	/* 操作按钮 */
	.action-buttons {
		display: flex;
		gap: 20rpx;
		margin-top: 30rpx;
	}
	
	.clear-btn, .scan-btn {
		flex: 1;
		background-color: #ff3b30;
		color: white;
		border-radius: 10rpx;
		font-size: 28rpx;
		padding: 25rpx;
	}
	
	.clear-btn:disabled {
		background-color: #cccccc;
	}
	
	.scan-btn {
		background-color: #007AFF;
	}
</style>